package ReflectionExample;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author: Cjj
 * @date: 2025/4/3
 */
public class ReflectionExample {
    public static void main(String[] args) throws Exception {
        //获取Class对象
        Class<?> clazz = Person.class;

        //创建对象
        Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
        Object person = constructor.newInstance("CJR", 22);

        //访问字段
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true);
        System.out.println("Name："+nameField.get(person));

        //修改字段
        //换行

        nameField.set(person,"英文：CJJ"+" 姓名：");
        System.out.println("Updated Name："+nameField.get(person));

        //调用方法
        Method greetMethod = clazz.getMethod("greet",String.class);
        greetMethod.invoke(person,"Hello");
    }

}
